#include "gd32w51x.h"
#include "stdint.h"
#include "DevicesRandom.h"


static uint32_t st_uiRandSeed = 123;


void vRandHardInit(void)
{
    /* TRNG module clock enable */
    rcu_periph_clock_enable(RCU_TRNG);

    /* TRNG registers reset */
    trng_disable();
    trng_deinit();
    trng_enable();
}

void vSrandHard(uint32_t uiRandSeed)
{
    (void)uiRandSeed;
}

uint32_t uiRandHard(void)
{
    uint32_t uiRand = 0;

    while((trng_flag_get(TRNG_FLAG_DRDY) == RESET) && (TRNG_CTL & TRNG_CTL_TRNGEN));

    uiRand = trng_get_true_random_data();

    /* 软件需要清除 CEIF/SEIF 位，之后将 TRNGEN 位清零并置 1 以便重新启动 TRNG 模块 */
    if((trng_flag_get(TRNG_FLAG_CECS | TRNG_FLAG_SECS) != RESET) || (uiRand == 0))
    {
        trng_interrupt_flag_clear(TRNG_INT_FLAG_CEIF | TRNG_INT_FLAG_SEIF);
        vRandHardInit();
    }

    return uiRand;
}

void vSrandSoft(uint32_t uiRandSeed)
{
    st_uiRandSeed = uiRandSeed;
}

uint32_t uiRandSoft(void)
{
    const uint32_t uiMultiplier = 1103515245, uiIncrement = 12345;

    /* 线性同余 */
    st_uiRandSeed = st_uiRandSeed * uiMultiplier + uiIncrement;

    return st_uiRandSeed;
}
